<template>
    <div class="app-container">
        <el-row>
            <el-col :span="24">
                <el-button type="text" @click="export2file()" class="btn-export">导出</el-button>
                <el-button type="text" @click="editable = !editable" class="btn-edit">编辑</el-button>
                <el-button type="text" @click="save()" class="btn-save">保存</el-button>
        </el-col>
        </el-row>
        
        <el-form ref="form" :model="form" label-width="100px">
            <el-form-item label="接口名称">
                <el-input v-model="form.interface_name" :disabled="!editable"></el-input>
            </el-form-item>
            <el-form-item label="接口代码">
                <el-input v-model="form.interface_code" :disabled="!editable"></el-input>
            </el-form-item>
            <el-form-item label="数据库名称">
                <el-input v-model="form.interface_db_name" :disabled="!editable"></el-input>
            </el-form-item>            
            <el-form-item label="数据库类型">
                <el-input v-model="form.interface_db_type" :disabled="!editable"></el-input>
            </el-form-item>            
            <el-form-item label="报表名称">
                <el-input v-model="form.report_name" :disabled="!editable"></el-input>
            </el-form-item>
            
            <el-form-item label="字段列表">

                <el-table v-loading="false" :data="field_page.data" border fit
                    highlight-current-row style="width: 100%">
                    <el-table-column align="center" v-for="item in columns" :key="item.id" :label="item.label">
                        <template slot-scope="{row}">
                            <el-input v-if="!item.read_only && editable" v-model="row[item.prop]" ></el-input>
                            <span v-else>{{ row[item.prop] }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column v-if="editable" label="操作" width="150" >
                      <template slot-scope="{row}">
                        <el-button type="text" @click="addField(row.interface_para_position)" >添加字段</el-button>
                        <el-button type="text" @click="deleteField(row)" >删除字段</el-button>
                      </template>
                    </el-table-column>
                </el-table>
                <pagination v-show="field_page.total > 0" :total="field_page.total" :page.sync="field_page.page" :limit.sync="field_page.limit"
                    @pagination="nextPage" :page-sizes=[10,20,50,100] />
            </el-form-item>
            <el-form-item label="接口SQL">
                <!-- <el-input type="textarea" v-model="form.interface_sql" :autosize="{ minRows: 10, maxRows: 100}"></el-input> -->
                    <!-- <SqlEditor ref="sqleditor" :value="form.interface_sql" :readOnly="editable"></SqlEditor> -->
                    <textarea ref="textarea"/>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import { getInterfaceDetail,updateInterface, exportInterface } from '@/api/report'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

import CodeMirror from 'codemirror'
import 'codemirror/addon/lint/lint.css'
import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/rubyblue.css'
import 'codemirror/addon/hint/show-hint.css'
import 'codemirror/lib/codemirror'
import 'codemirror/addon/lint/lint'
import 'codemirror/mode/sql/sql'
import 'codemirror/addon/hint/sql-hint'
import 'codemirror/addon/hint/show-hint'


export default {
    components: { Pagination },
    props: {
        id: {
            type: String,
        }
    },
    data() {
        return {
            sqlEditor: null,
            editable: false,
            form: {
                interface_name: '',
                interface_code: '',
                interface_sql: '',
                is_date_option: '',
                is_paging: '',
                is_second_table: false,
                interface_fields: []
            },
            field_page: {
                data: [],
                total: 0,
                page: 1,
                limit:10
            },
            columns: [
            // {id:1,prop:"id",label:"参数id", read_only: true},
            // {id:2,prop:"interface_id",label:"接口id"},
            {id:3,prop:"interface_para_code",label:"参数编码"},
            {id:4,prop:"interface_para_name",label:"参数名称"},
            {id:5,prop:"interface_para_position",label:"参数位置"},
            {id:6,prop:"interface_para_type",label:"参数类型"},
            {id:7,prop:"interface_data_type",label:"数据类型"},
            {id:8,prop:"interface_para_default",label:"默认值"},
            {id:9,prop:"interface_cascade_para",label:"级联参数"},
            {id:10,prop:"interface_export_flag",label:"是否导出"},
            {id:11,prop:"interface_para_desc",label:"参数描述"},
            {id:12,prop:"interface_para_interface_code",label:"接口参数编码"},
            // {id:13,prop:"interface_para_rowspan",label:""},
            // {id:14,prop:"interface_parent_name",label:""},
            // {id:15,prop:"interface_parent_position",label:""},
            // {id:16,prop:"interface_show_desc",label:""},
            // {id:17,prop:"interface_show_flag",label:""}
            ]
        }
    },
    mounted() {
        this.getInterface()
        this.sqlEditor = CodeMirror.fromTextArea(this.$refs.textarea, {
            mode: 'text/x-sql',
            matchBrackets: true,
            styleActiveLine: true,
            indentWithTabs: true,
            smartIndent: true,
            lineNumbers: true,
            spellcheck: true,
            lineWrapping: true,
            resetSelectionOnContextMenu: true,
            autofocus: true,
            indentUnit: 4,
            dragDrop: true,
            theme: 'rubyblue',
            autorefresh: true,
            extraKeys: {
                'Ctrl': 'autocomplete',
                Tab: function (cm) {
                    let spaces = Array(cm.getOption('indentUnit') + 1).join(' ');
                    cm.replaceSelection(spaces);
                },
            },
            hintOptions: { completeSingle: this.completeSingle },
        })

        // CodeMirror.signal(this.sqlEditor, 'cursorActivity', function (cm) {
            // cm.setsize(null, 1000)
        // })
    },
    watch: {
        editable(val) {
            this.sqlEditor.setOption('readOnly', !val)
            this.sqlEditor.refresh()
        }
    },
    methods: {
        async getInterface() {
            let interface_id = this.id
        await getInterfaceDetail({ interface_id }).then(response => {
          this.form = response.data
          if (this.form) {
                this.sqlEditor.setValue(this.form.interface_sql)
            //   let line_size = this.form.interface_sql.split('\n').length
                let line_size = window.innerHeight
                //   console.log(line_size)
                  this.sqlEditor.setSize(null, line_size)
                  this.sqlEditor.setOption('readOnly', !this.editable)
                  this.sqlEditor.refresh()
            }
          else {
            alert('接口不存在')
                this.$store.commit
              }
            })
            this.nextPage()
        },
        handleSubmit() {
            // updateInterface(this.form).then(response => {
            //     alert(response.msg)
            // })
        },
        nextPage() {
            let currentPage = this.field_page.page || 1
            let currentLimit = this.field_page.limit || 10
            const startIndex = (currentPage - 1) * currentLimit
            const endIndex = startIndex + currentLimit
            this.field_page.data = this.form.interface_fields.slice(startIndex, endIndex)
            this.field_page.total = this.form.interface_fields.length
        },
        save() {
            if (this.editable) {
                this.editable = false
                this.form.interface_sql = this.sqlEditor.getValue()
                console.log(this.form)
              updateInterface(this.form).then(response => {
                    this.$message("保存成功")
                })
            }
        },
        export2file() {
            exportInterface({ interface_id: this.id }).then(response => {
                alert(response.msg)
            })
        },
      addField(position) {
            this.form.interface_fields.push({
				"id": undefined,
				"interface_id": this.id,
				"interface_para_code": "",
				"interface_para_name": "",
				"interface_para_type": "",
				"interface_data_type": "",
				"interface_para_default": "",
				"interface_para_desc": null,
				"interface_para_interface_code": null,
				"interface_para_position": position+1,
        "interface_para_rowspan": null,
        "interface_parent_name": null,
        "interface_parent_position":null,
				"interface_show_flag": "否",
				"interface_export_flag": "否",
            })
            this.field_page.page = 1
            this.field_page.total = this.form.interface_fields.length
            this.nextPage()
      },
      deleteField() {
        
      },
        editField({ row, column, cell, event}) {
            console.log(row, column, cell, event)
        }
    }
}
</script>

<style lang="css" scoped>

.app-container .CodeMirror  {
    height: auto;
}

.item {
    background-color: #fdfdfd;
    border: solid 1px #eee;
    cursor: move;
}

/*选中样式*/
.chosen {
    border: solid 1px #3089dc !important;
}


.btn-edit , .btn-save ,.btn-export{
    float: right;
  padding: 10px;
  cursor: pointer;
  margin: 10px;
}




</style>